package com.tikeyc.flutterandroid.custom;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.util.HashMap;

import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.EventChannel;

/*EventChannel用于从Native向Flutter发送通知事件
 *例如Flutter通过其监听Android的重力感应变化等。
 *与MethodChannel不同，EventChannel是Native到Flutter的单向调用，调用是一对多的，类似Android的BrodcastReceiver
* */
public class MyEventChannel {
    public static final String Event_Channel = "com.tikeyc.fluttermodule/eventChannel";

    public EventChannel eventChannel;

    public EventChannel.EventSink eventSink;

    public MyEventChannel(EventChannel eventChannel) {
        this.eventChannel = eventChannel;
    }

    public static MyEventChannel instance(FlutterEngine flutterEngine) {
        EventChannel eventChannel = new EventChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), Event_Channel);
        return new MyEventChannel(eventChannel);
    }

    public static MyEventChannel instance(FlutterEngine flutterEngine, String name) {
        EventChannel eventChannel = new EventChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), name);
        return new MyEventChannel(eventChannel);
    }

    public MyEventChannel registerEventChannel() {
        // 在StreamHandler#onLister回调中获取EventSink引用并保存
        eventChannel.setStreamHandler(new EventChannel.StreamHandler() {
            @Override
            public void onListen(Object arguments, EventChannel.EventSink events) {
                eventSink = events;
            }

            @Override
            public void onCancel(Object arguments) {
                eventSink = null;
            }
        });
        return this;
    }

    public void getNetWorkType(Context context) {
        if (eventSink == null) {
            return;
        }
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if(info != null) {
            HashMap params = new HashMap<>();
            params.put("type", "networkInfo");
            if(info.getType() == ConnectivityManager.TYPE_WIFI) {
                //3.调用eventSink.success向Flutter端发送消息
                params.put("value", "WIFI");
            } else if(info.getType() == ConnectivityManager.TYPE_MOBILE) {
                params.put("value", "Mobile");
            } else {
                params.put("value", "Unkonw");
            }
            eventSink.success(params);
        } else {
            //3.报错后调用eventSink.error向Flutter端发送消息
            eventSink.error("error network", "error network", "error network");
        }
    }
}
